<!--
 * @Description: 病虫害信息
-->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="29"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading" :listData="tableData"
        @handleSelectionChange="handleSelectionChange">
        <template v-slot:operation="{ row }">
          <template v-if="!row.index">
            <el-button
              v-if="judgePermission(29, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edits(row)"
            >
              <i class="el-icon-edit-outline"></i> 修 改
            </el-button>
            <el-button
              v-if="judgePermission(29, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="delmessage(row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </template>
        <template v-slot:img="{ row }">
          <template v-if="!row.index">
            <el-button
              v-if="row.pictureId"
              type="success"
              @click="getpicmessage(row.pictureId)"
            >点击查看</el-button>
            <span v-else>暂无图片</span>
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText + farmingTypeTitles + '记录'"
        :visible.sync="dialogFormVisible"
        width="30%"
        @close="cancel"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item
            :label="`${farmingTypeTitles}类别: `"
            prop="alarmTypeName"
            class="w50p"
          >
            <el-select
              v-model="formData.alarmTypeName"
              clearable
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in (farmingTypeTitles === '病害'?alarmTypeLists:alarmTypeList)"
                :key="index"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="`${farmingTypeTitles}名称: `"
            prop="name"
            class="w50p"
          >
            <el-input
              v-model="formData.name"
              clearable
            />
          </el-form-item>
          </el-form-item>
          <el-form-item
            :label="`${farmingTypeTitles}描述: `"
            prop="content"
            class="w100p"
          >
            <el-input
              v-model="formData.content"
              clearable
            />
          </el-form-item>
          <el-form-item
            :label="`${farmingTypeTitles}图片：`"
            class="w50p"
          >
            <ele-upload-image
              v-model="images"
              multiple
              :response-fn="handleResponse"
              :before-remove="handleRemove"
              :headers="headers"
              :file-size="10"
              :action="ImageUrl()"
            />
          </el-form-item>
        </el-form>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            class="zh-button-one"
            @click="cancel"
          >取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save"
          >确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="图片"
        :visible.sync="showpicview"
        width="30%"
        v-loading="imgloading"
      >
        <img
          v-for="item,index in pictviewurl"
          :key="index"
          style="max-width: 100%;"
          :src="`data:image/png;base64,${item.pictureData}`"
        />
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            class="zh-button-one"
            @click="showpicview = false"
          >取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="showpicview = false"
          >确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import pestInfoApi from "@/api/basic-info-manage/pest-info/index";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
import { farmingTypeTitle } from "@/utils/validate";
import { getToken } from "@/utils/auth";
import baseURL from "@/api/baseURL";
export default {
  name: "PestRecords",
  components: { SearchForm, Table, ActionBar, Pagination, BaseMainSlot },
  mixins: [mymixin],
  data() {
    var farmingTypeTitles = farmingTypeTitle()
    return {
      tableColumn: [
        { prop: 'alarmTypeName', label: farmingTypeTitles+'类别' },
        { prop: 'name', label: farmingTypeTitles+'名称' },
        { prop: 'content', label: farmingTypeTitles+'描述' },
        { prop: 'pictureId', label: farmingTypeTitles+'图片', slotName: 'img' },
        { prop: 'operation', label: '操作', slotName: 'operation', width: "140" }
      ],
      formConfig: [
        {
          label: '病虫害类别',
          prop: 'alarmTypeName',
          type: 'select',
          options: [
            { label: '病害' },
            { label: '虫害' },
          ],
          optionKey: { label: 'label', value: 'label' }
        }, {
          label: '病虫害名称',
          prop: 'name',
          type: 'input',
        }, 
      ],
      showpicview: false,
      pictviewurl: [],
      farmingTypeTitles: farmingTypeTitle(),
      // 异常原因
      alarmTypeList: [
        { name: "病害", value: 0 },
        { name: "虫害", value: 1 }
      ],
      // 异常原因
      alarmTypeLists: [{ name: "病害", value: 0 }],
      // 所搜索框内容
      searchlist: {},
      rules: {
        alarmTypeName: [
          { required: true, message: "请选择"+farmingTypeTitles+"类别", trigger: "change" }
        ],
        name: [
          { required: true, message: "请输入"+farmingTypeTitles+"名称", trigger: "change" }
        ],
      },
      // 当前表格选择的数组
      nowSelectList: [],
      // 上传图片
      images: [],
      imgloading: false,
    };
  },
  computed: {
    headers() {
      return {
        accessToken: sessionStorage.getItem("token"),
        organizationNo: sessionStorage.organizationNo,
        sysDataBaseName: sessionStorage.databaseName
      };
    },
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    dialogFormVisible(v) {
      if (v) {
        this.$nextTick(()=>{
          this.$refs.formData.clearValidate()
        })
      }
    }
  },
  created() {

  },
  mounted() {
    this.getTableDataList();
  },
  methods: {
    // 图片地址
    ImageUrl() {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        let URL = `${baseURL.webServiceUrl}v3/patrol/picture/addMultipart`;
        return URL;
      } else {
        let URL = "#";
        return URL;
      }
    },
    handleResponse(res) {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        !this.formData.pictureId && (this.formData.pictureId = [])
        this.formData.pictureId.push(res.data);
        pestInfoApi.queryPicture(res.data).then(res => {
          this.images = this.images.slice(0, this.images.length-1)
          this.images.push("data:image/png;base64," + res.data.pictureData);
        });
        return this.images;
      } else {
        return this.$message.error("点击修改按钮再进行编辑!");
      }
    },
    handleRemove(file, fileList) {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        let index = this.images.findIndex(el => { return el == file })
        console.log(file)
        this.formData.pictureId.splice(index, 1)
      } else {
        return this.$message.error("点击修改按钮再进行编辑!");
      }
    },
    // 表格查询
    getTableDataList() {
      this.loading = true;
      this.tableData = [];
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
        entity: {
          // disposeAction: 1,
          organizationNo: getToken("organizationNo"),
          name: this.searchlist.name,
          alarmTypeName: this.searchlist.alarmTypeName
        }
      };
      this.entity = params.entity
      pestInfoApi.queryPageByCondition(params).then(res => {
        if (res.code === 1) {
          // this.$message.success('查询成功')
        } else {
          this.$message.error("查询失败");
        }
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
        this.addblankmet();
        this.resetActionBar();
      });
    },
    // 获取图片详情
    getpicmessage(id) {
      this.showpicview = true;
      this.imgloading = true;
      pestInfoApi.queryPictureList(id).then(res => {
        this.pictviewurl = res.data
        this.imgloading = false;
      });
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    edits(e) {
      this.formData = { ...e };
      this.nowChanceStau = "edit";
      this.titleText = "修改";
      this.dialogFormVisible = true;
      this.canInput = true;
      this.addActive = false;
      this.delActive = false;
      this.saveActive = true;
      this.cancelActive = true;
      this.editActive = false;
      this.images = []
      this.formData.pictureId &&
      pestInfoApi.queryPictureList(this.formData.pictureId).then(res => {
        this.images = res.data.map(el => {
          return "data:image/png;base64," + el.pictureData;
        })
      });
      this.formData.pictureId = this.formData.pictureId.split(',')
    },
    // 删除时触发方法
    delmessage(e) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          let list = e ? [e.insectId] : this.nowSelectList
          pestInfoApi.delListById(list).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.getTableDataList();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs["formData"].validate(valid => {
        if (valid) {
          console.log(this.formData.pictureId)
          this.formData.pictureId = this.formData.pictureId?.join(',')
          if (this.nowChanceStau === "edit") {
            pestInfoApi.edit(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.search();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            pestInfoApi.add({ ...this.formData }).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.search();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    handleSelectionChange(list) {
      this.nowSelectList = [];
      this.nowSelectList = list.map(item => item.insectId)
      if (this.nowSelectList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-checkbox {
  .el-checkbox__label {
    color: #dbe9e9;
    color: #d3e01c;
    // flex-direction: column;
  }
}
::v-deep .el-dialog {
  .el-dialog__header .el-dialog__title {
    color: #dbe9e9;
  }
  background-color: #005d7b;
  border: #23fff8 1px solid;
  white-space: nowrap;
  ::v-deep .el-input__inner {
    color: #dbe9e9 !important;
  }
}
::v-deep .el-image__error {
  display: none;
}
::v-deep .el-upload__tip {
  display: none;
}
</style>
